import axios from "axios";
import store from "@/store";
import storage from "store";
import qs from "qs";
import notification from "ant-design-vue/es/notification";
import { VueAxios } from "./axios";
import { ACCESS_TOKEN, USER_INFO } from "@/store/mutation-types";

import router from "../router";
import configs from "@/config/defaultSettings";
import vues from "@/main";

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_API_BASE_URL,
  // timeout: 10, // 请求超时时间
  timeout: 5 * 60 * 1000, // 请求超时时间
  headers: {
    "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
  }
  // responseType:'blob'
});

// 异常拦截处理器
const errorHandler = error => {
  console.log("请求错误---", error);
  //请求超时，请求错误，报错处理，关闭loading
  if (
    error.code === "ECONNABORTED" ||
    error.message === "Network Error" ||
    error.message.includes("timeout")
  ) {
    notification.error({
      message: "提示",
      description: "请求超时，请稍后重试"
    });
    vues.$loading.hide();
    // return {
    //   code:111,
    //   data:null
    // };
  }
  if (error.response) {
    const data = error.response.data;
    // 从 localstorage 获取 token
    const token = storage.get(ACCESS_TOKEN);
    if (error.response.status === 403) {
      notification.error({
        message: "提示",
        description: data.message
      });
    }

    if (
      error.response.status === 401 &&
      !(data.result && data.result.isLogin)
    ) {
      notification.error({
        message: "提示",
        description: data.message
      });
      if (token) {
        store.dispatch("Logout").then(() => {
          setTimeout(() => {
            window.location.reload();
          }, 1500);
        });
      }
    }
  }
  return Promise.reject(error);
};



// request interceptor  请求拦截
request.interceptors.request.use(config => {
  // 文档接口 axios 对象添加 blob
  if (config.url == "/cms/incentivePlan/getSignatureDocTemplet") {
    config.responseType = "blob";
  }
  if (config.url != "/cms/incentivePlan/getSignatureDocTemplet") {
    config.responseType = "";
  }

  const token = storage.get(ACCESS_TOKEN);
  // console.log('获取本地token',token)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  config.headers["source"] = configs.source; //类型
  if (token) {
    // config.headers['Access-Token'] = token
    config.headers["tokenId"] = token;
  }
  // console.log('请求参数',config.data)
  // for (var key in config.data) {
  //   if (config.data[key] === "") {
  //     delete config.data[key];
  //   }
  // }
  config.data = qs.stringify(config.data);
  return config;
}, errorHandler);



// response interceptor   响应拦截
request.interceptors.response.use(response => {
  // console.log('response------', response)
  // 文档接口 没有响应体 直接返回文件流
  if (response.config.url == "/cms/incentivePlan/getSignatureDocTemplet") {
    return response.data;
  } //  判断登录失效
  else if (response.data.code == 100003) {
    vues.$loading.hide();
    // notification.error({
    //   message: '提示',
    //   description: response.data.msg
    // })
    storage.remove(ACCESS_TOKEN);
    storage.remove(USER_INFO);
    router.push("/user/login");
    return;
  } else if (response.data.code == 10014) {
    //账号密码错误
    vues.$loading.hide();
    notMsg(response.data.msg);
  } else if (response.data.code == 100065) {
    //企业未认证
    vues.$loading.hide();
    notMsg(response.data.msg);
    router.push("/company/setting/index");
  } else if (response.data.code == 100061) {
    //用户未认证
    vues.$loading.hide();
    notMsg(response.data.msg);
    router.push("/user_info/user_index");
  } else if (response.data.code == 100047) {
    //用户未绑定邮箱
    vues.$loading.hide();
    notMsg(response.data.msg);
    router.push("/user_info/user_index");
  } else if (response.data.code == 100049) {
    //请完成实名认证
    vues.$loading.hide();
    notMsg(response.data.msg);
    router.push("/user_info/user_index");
  } else if (response.data.code !== 0) {
    //抛出 一切错误
    vues.$loading.hide();
    notMsg(response.data.msg);
  }
  return response.data;
}, errorHandler);

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, request);
  }
};

function notMsg(msg) {
  notification.error({
    message: "提示",
    description: msg
  });
}

export default request;

export { installer as VueAxios, request as axios };
